package com.bbcare.followup.plat.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ToolUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.comm.enumeration.MessageReadStatusEnum;
import com.bbcare.comm.enumeration.MessageTypeEnum;
import com.bbcare.comm.enumeration.PushTypeEnum;
import com.bbcare.followup.plat.dto.request.MessageNotifyRecordReqDTO;
import com.bbcare.followup.plat.entity.FuMilkPreparationRecord;
import com.bbcare.followup.plat.entity.MessageNotifyRecord;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PtUserSharePhoto;
import com.bbcare.followup.plat.entity.model.CommonPushMessage;
import com.bbcare.followup.plat.entity.model.Message;
import com.bbcare.followup.plat.service.IMessageNotifyRecordService;
import com.bbcare.followup.plat.store.ibatis.IMessageNotifyRecordDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 消息通知服务实现
 */
@Service
@Transactional
public class MessageNotifyRecordServiceImpl implements IMessageNotifyRecordService {
    private final Log logger = LogFactory.getLog(MessageNotifyRecordServiceImpl.class);

    @Autowired
    private IMessageNotifyRecordDAO messageNotifyRecordDAO;

    @Autowired
    private IPatientDAO patientDao;

    @Override
    public Map<String, Object> listPage(MessageNotifyRecordReqDTO reqDTO, HttpServletRequest request) {
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId   = sessionMap.get("tenantId").toString();
        HashMap<String, Object> paramMap = Dict.parse(reqDTO);
        Integer  currentPage= reqDTO.getCurrentPage() == null ? 1 : reqDTO.getCurrentPage();
        Integer  pageSize = reqDTO.getPageSize() == null ? 10 : reqDTO.getPageSize();
        paramMap.put("tenantId", tenantId);
        PageHelper.startPage(currentPage, pageSize);
        List<MessageNotifyRecord> list = null;
        if (tenantId.equalsIgnoreCase("fddxekyyzzta001")) {
            //复旦。
            list    = messageNotifyRecordDAO.selectPage(paramMap);
        } else {
            //其他。
            list    = messageNotifyRecordDAO.selectPage1(paramMap);
        }
        PageInfo<MessageNotifyRecord> page = new PageInfo<>(list);
        HashMap<String, Object> responseMap = MapUtil.newHashMap();
        responseMap.put("data", list);
        responseMap.put("count", page.getTotal());
        return responseMap;
    }

    @Override
    public void markMessageNotifyRead(String id) {
        //预先处理标记过期
        MessageNotifyRecord messageNotifyRecord = messageNotifyRecordDAO.selectByPrimaryKey(id);
        if (ObjectUtil.isNull(messageNotifyRecord)) {
            throw new AppException("1000", "数据不存在");
        }
        messageNotifyRecord.setStatus(MessageReadStatusEnum.FINISH_READ.getValue());
        messageNotifyRecord.setReadTime(DateUtil.date());
        messageNotifyRecord.setUpdateTime(DateUtil.date());
        messageNotifyRecordDAO.updateByPrimaryKeySelective(messageNotifyRecord);
    }

    @SneakyThrows
    @Override
    public void sendMessage(JSONObject jsonObject){

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", jsonObject.getString("userId"));
        Patient patient = patientDao.selectById(map);

        MessageNotifyRecord record = new MessageNotifyRecord();
        record.setId(IdUtil.getSnowflake(1,1).nextIdStr());
        record.setSourceId((String) jsonObject.get("userId"));
        record.setUserId((String) jsonObject.get("userId"));
        record.setUserName(patient.getUserName());
        record.setGender(patient.getGender());
        record.setPhone(patient.getPhoneNo());
        record.setType((Integer) jsonObject.get("type"));
        record.setTaskId(null);
        record.setTaskName("");
        record.setStatus(MessageReadStatusEnum.NO_READ.getValue());
        record.setPushType(PushTypeEnum.WX_GZH.getValue());
        record.setTenantId((String) jsonObject.get("tenantId"));
        record.setAccountId(patient.getAccountId());
        record.setSendTime(DateUtil.date());
        record.setReadTime(null);
        record.setCreateTime(DateUtil.date());
        record.setUpdateTime(DateUtil.date());
        record.setRemark((String) jsonObject.get("content"));
        messageNotifyRecordDAO.insert(record);

        String sendMsg = null;
        JSONObject msJsonObject = new JSONObject();
        msJsonObject.put("userId",patient.getId());
        msJsonObject.put("userName",patient.getUserName());
        msJsonObject.put("sendTime",record.getSendTime());
        msJsonObject.put("content",record.getRemark());
        msJsonObject.put("platType",jsonObject.get("platType"));
        msJsonObject.put("type",jsonObject.get("type"));
        sendMsg = msJsonObject.toJSONString();
        if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl")))  {
            //如果config.properties中有redirectUrl配置项，才会发送请求。没有配置项，就不发送了。
            com.bbcare.comm.HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,sendMsg);
        }
    }

    /**
     * 发送备乳通知消息给小程序。
     * Updated by Michael on 2022-08-01.
     * @param fuMilkPreparationRecord
     */
    @SneakyThrows
    @Override
    public void sendMilkPreparationMessage(FuMilkPreparationRecord fuMilkPreparationRecord, String platType) {
        MessageNotifyRecord messageNotifyRecord = addMilkPrepMessageNotifyRecord(fuMilkPreparationRecord, MessageTypeEnum.BRTZ.getValue());
        String sendMsg = null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId",fuMilkPreparationRecord.getUserId());
        jsonObject.put("messageNotifyId",messageNotifyRecord.getId());
        jsonObject.put("milkMsg",fuMilkPreparationRecord.getMilkMsg());
        jsonObject.put("fuMilkPreparationId",fuMilkPreparationRecord.getId());
        jsonObject.put("platType",Integer.parseInt(platType));
        jsonObject.put("type",20);
        sendMsg = jsonObject.toJSONString();
        if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl")))  {
            //如果config.properties中有redirectUrl配置项，才会发送请求。没有配置项，就不发送了。
            com.bbcare.comm.HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,sendMsg);
        }
        messageNotifyRecord.setSendTime(DateUtil.date());
        messageNotifyRecordDAO.updateByPrimaryKeySelective(messageNotifyRecord);
    }

    /**
     *
     * @param ptUserSharePhoto 宝宝照片（成长足迹）。
     * Updated by Michael on 2022-08-01.
     */
    @SneakyThrows
    @Override
    public void sendUserSharePhotoMessage(PtUserSharePhoto ptUserSharePhoto, String platType) {
        //发送照片记录通知
        //新增照片记录
        MessageNotifyRecord messageNotifyRecord = addSharePhotoMessageNotifyRecord(ptUserSharePhoto, MessageTypeEnum.ZPJL.getValue());
        String sendMsg = null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("messageNotifyId",messageNotifyRecord.getId());
        jsonObject.put("userId",ptUserSharePhoto.getUserId());
        jsonObject.put("platType",Integer.parseInt(platType));

        jsonObject.put("type",19);
        sendMsg = jsonObject.toJSONString();
        if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl")))  {
            //如果config.properties中有redirectUrl配置项，才会发送请求。没有配置项，就不发送了。
            com.bbcare.comm.HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,sendMsg);
        }
        messageNotifyRecord.setSendTime(DateUtil.date());
        messageNotifyRecordDAO.updateByPrimaryKeySelective(messageNotifyRecord);
    }

    /**
     * 保存备乳供应通知
     *
     * @param fuMilkPreparationRecord
     * @param type
     * @return
     */
    private MessageNotifyRecord addMilkPrepMessageNotifyRecord(FuMilkPreparationRecord fuMilkPreparationRecord, Integer type) {
        MessageNotifyRecord messageNotifyRecord = new MessageNotifyRecord();
        messageNotifyRecord.setId(IdUtil.getSnowflake(1,1).nextIdStr());
        messageNotifyRecord.setSourceId(fuMilkPreparationRecord.getId());
        messageNotifyRecord.setUserId(fuMilkPreparationRecord.getUserId());
        messageNotifyRecord.setUserName(fuMilkPreparationRecord.getUserName());
        messageNotifyRecord.setGender(fuMilkPreparationRecord.getGender());
        messageNotifyRecord.setPhone(fuMilkPreparationRecord.getPhone());
        messageNotifyRecord.setType(type);
        messageNotifyRecord.setTaskId(null);
        messageNotifyRecord.setTaskName("");
        messageNotifyRecord.setStatus(MessageReadStatusEnum.NO_READ.getValue());
        messageNotifyRecord.setPushType(PushTypeEnum.WX_GZH.getValue());
        messageNotifyRecord.setTenantId(fuMilkPreparationRecord.getTenantId());
        messageNotifyRecord.setAccountId(fuMilkPreparationRecord.getAccountId());
        messageNotifyRecord.setSendTime(null);
        messageNotifyRecord.setReadTime(null);
        messageNotifyRecord.setCreateTime(DateUtil.date());
        messageNotifyRecord.setUpdateTime(DateUtil.date());
        messageNotifyRecord.setRemark("备乳通知记录");
        messageNotifyRecordDAO.insert(messageNotifyRecord);
        return messageNotifyRecord;
    }

    private MessageNotifyRecord addSharePhotoMessageNotifyRecord(PtUserSharePhoto ptUserSharePhoto, Integer type) {
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", ptUserSharePhoto.getUserId());
        Patient ptVo = null;
        try {
             ptVo = patientDao.selectById(userMapIn);
        } catch (Exception e) {
            throw new AppException("1001","用户信息有误");
        }
        MessageNotifyRecord messageNotifyRecord = new MessageNotifyRecord();
        messageNotifyRecord.setId(IdUtil.getSnowflake(1,1).nextIdStr());
        messageNotifyRecord.setSourceId(ptUserSharePhoto.getId());
        messageNotifyRecord.setUserId(ptUserSharePhoto.getUserId());
        messageNotifyRecord.setUserName(ptVo.getUserName());
        messageNotifyRecord.setGender(ptVo.getGender());
        messageNotifyRecord.setPhone(ptVo.getPhoneNo());
        messageNotifyRecord.setType(type);
        messageNotifyRecord.setTaskId(null);
        messageNotifyRecord.setTaskName("");
        messageNotifyRecord.setStatus(MessageReadStatusEnum.NO_READ.getValue());
        messageNotifyRecord.setPushType(PushTypeEnum.WX_GZH.getValue());
        messageNotifyRecord.setTenantId(ptUserSharePhoto.getTenantId());
        messageNotifyRecord.setAccountId(ptUserSharePhoto.getAccountId());
        messageNotifyRecord.setSendTime(null);
        messageNotifyRecord.setReadTime(null);
        messageNotifyRecord.setCreateTime(DateUtil.date());
        messageNotifyRecord.setUpdateTime(DateUtil.date());
        messageNotifyRecord.setRemark("照片记录");
        messageNotifyRecordDAO.insert(messageNotifyRecord);
        return messageNotifyRecord;
    }

}
